package com.example.moneygrosService;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.os.Messenger;
import android.os.Process;
import android.os.RemoteException;
import android.provider.BaseColumns;
import android.util.Log;
import android.widget.Toast;

import com.example.moneygrosService.MainActivityService.DB_TOKEN;
import com.example.moneygrosService.MainActivityService.REQUEST_CODES;
import com.example.moneygrosService.database.MoneyContract;
import com.example.moneygrosService.database.MoneyContract.UserProfiles;
import com.example.moneygrosService.database.MoneyContract.UserProfilesColumns;

public class DatabaseService extends Service {
	private static final String TAG = DatabaseService.class.getSimpleName();
    
	private NotificationManager nm;    
	private MoneyServiceAsyncQueryHandler mMoneyServiceAsyncQueryHandler;
	private ContentResolver mContentResolver;

    static final int MSG_REGISTER_CLIENT = 1;
    static final int MSG_UNREGISTER_CLIENT = 2;

	static private boolean isRunning;

	private Looper mServiceLooper;
	static private ServiceHandler mServiceHandler;
	private Messenger mMessenger;
	private Messenger mClient;

	// Handler that receives messages from the thread
	private final class ServiceHandler extends Handler {
		public ServiceHandler(Looper looper) {
			super(looper);
		}

		@Override
		public void handleMessage(Message msg) {
			mClient = msg.replyTo;
			Bundle data = msg.getData();
//			int requestCode = data.getInt("request_code");
			//	  			int RESULT_OK = 0;//dummy
			//	  			if(requestCode==RESULT_OK){
			Log.v(TAG, "message received");
			User user;
			switch (msg.what){
			case REQUEST_CODES.SERVICE_CHECK_USER_PROFILE: 
				Log.v(TAG, "SERVICE_CHECK_USER_PROFILE");
				startModifyUserProfile();
				break;
			case REQUEST_CODES.SERVICE_MODIFY_USER_PROFILE: 
				Log.v(TAG, "SERVICE_MODIFY_USER_PROFILE");
				user = data.getParcelable("user");//remplir avec la valeur venue de l'appel

				insertOrUpdateUserProfile(user);
				break;
			default:
				super.handleMessage(msg);
			}

			// Stop the service using the startId, so that we don't stop
			// the service in the middle of handling another job
//			stopSelf(msg.arg1);
		}
	}

	public DatabaseService() {
		// TODO Auto-generated constructor stub
		isRunning=false;
	}

	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return mMessenger.getBinder();
	}

	@Override
	public void onCreate() {
		Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
		Log.d(TAG, "onCreate");

		mContentResolver = getContentResolver();
		mMoneyServiceAsyncQueryHandler = new MoneyServiceAsyncQueryHandler(mContentResolver, this);

		// Start up the thread running the service.  Note that we create a
		// separate thread because the service normally runs in the process's
		// main thread, which we don't want to block.  We also make it
		// background priority so CPU-intensive work will not disrupt our UI.
		HandlerThread thread = new HandlerThread("ServiceStartArguments",
				Process.THREAD_PRIORITY_BACKGROUND);
		thread.start();

		// Get the HandlerThread's Looper and use it for our Handler 
		mServiceLooper = thread.getLooper();
		mServiceHandler = new ServiceHandler(mServiceLooper);
		mMessenger= new Messenger(mServiceHandler);

        showNotification();
	}

	@Override
	public void onStart(Intent intent, int startid) {		
		Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show();
	
		Log.d(TAG, "onStart");
		isRunning=true;
	}

	@Override
		public int onStartCommand(Intent intent, int flags, int startId) {
			Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show();
			Log.d(TAG, "onStartCommand");
			
			// For each start request, send a message to start a job and deliver the
			// start ID so we know which request we're stopping when we finish the job
	//		Message msg = mServiceHandler.obtainMessage();
	//		msg.arg1 = startId;
	//		mServiceHandler.sendMessage(msg);
	
			isRunning=true;
			// If we get killed, after returning from here, restart
			return START_STICKY;
		}

	@Override
	public void onDestroy() {
		Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();
		Log.d(TAG, "onDestroy");
		isRunning = false;
        nm.cancel(R.string.notif_service_started); // Cancel the persistent notification.
	}

	private void insertOrUpdateUserProfile(User user){
		//requete d'existence de l'utilisateur
		String[] projection = {BaseColumns._ID, UserProfilesColumns.USER_ID, UserProfilesColumns.USER_NAME, UserProfilesColumns.PHONE_NUMBER, UserProfilesColumns.VERSION};
		String selection = MoneyContract.UsersColumns.USER_ID+"=?";
		String[] selectionArgs= {user.getUser_id()};
		mMoneyServiceAsyncQueryHandler.startQuery(DB_TOKEN.CHECK_USER_UPDATE_USER_PROFILE, (Object) user, UserProfiles.CONTENT_URI, projection, selection, selectionArgs, null);       
	}

	
	
	public static boolean isRunning()
	{
		return isRunning;
	}
	 private void showNotification() {
	        nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
	        // In this sample, we'll use the same text for the ticker and the expanded notification
	        CharSequence text = getText(R.string.notif_service_started); 
	        // Set the icon, scrolling text and timestamp
	        Notification notification = new Notification(R.drawable.ic_launcher, text, System.currentTimeMillis());
	        // The PendingIntent to launch our activity if the user selects this notification
	        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, MainActivityService.class), 0);
	        // Set the info for the views that show in the notification panel.
	        notification.setLatestEventInfo(this, getText(R.string.notif_service_label), text, contentIntent);
	        // Send the notification.
	        // We use a layout id because it is a unique number.  We use it later to cancel.
	        nm.notify(R.string.notif_service_started, notification);
	    }
	 
	 
	    private void startModifyUserProfile() {
	    	String[] projection = {BaseColumns._ID, UserProfilesColumns.USER_ID, UserProfilesColumns.USER_NAME, UserProfilesColumns.PHONE_NUMBER, UserProfilesColumns.VERSION};
	    		    	
	    	mMoneyServiceAsyncQueryHandler.startQuery(DB_TOKEN.CHECK_USER_PROFILE_FOR_ACTIVITY, null, UserProfiles.CONTENT_URI, projection, null, null, null);

		}

		public void updateUserProfile(User user) {
			ContentValues values = new ContentValues();
			values.put(MoneyContract.UserProfilesColumns.USER_NAME, user.getUser_name());
			values.put(MoneyContract.UserProfilesColumns.VERSION, user.getVersion());
			values.put(MoneyContract.UserProfilesColumns.PHONE_NUMBER, user.getPhone_number());
			values.put(MoneyContract.UserProfilesColumns.BLUETOOTH_MAC, user.getBluetooth_MAC());
			String selection = MoneyContract.UsersColumns.USER_ID+"=?";
			String[] selectionArgs= {user.getUser_id()};
			mMoneyServiceAsyncQueryHandler.startUpdate(DB_TOKEN.UPDATE_USER_PROFILE, user, UserProfiles.CONTENT_URI, values, selection, selectionArgs);
		}

		public void insertUserProfile(User user) {
	        ContentValues values = user.getProfileContentValues();
			mMoneyServiceAsyncQueryHandler.startInsert(DB_TOKEN.INSERT_USER_PROFILE, (Object)user,UserProfiles.CONTENT_URI, values);
		}

		public void sendMsg(Bundle bundle) {
            
            Message msg = Message.obtain();
            msg.setData(bundle);
            try {
				mClient.send(msg);
			} catch (RemoteException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
}
